package com.kexun.mvc.listen;

import com.kexun.annotation.RequestMapping;
import com.kexun.mvc.container.Containers;
import com.kexun.mvc.resolvers.*;
import com.kexun.utils.ClassUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author KEXUN
 */
public class InitMapping implements ServletContextListener {

    public static void main(String[] args) {
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //扫描controller包到容器
        Set<Class<?>> classes = ClassUtils.getClasses("com.kexun.controller");
        for (Class<?> aClass : classes) {
            RequestMapping classMapping = aClass.getAnnotation(RequestMapping.class);
            String classMappingVal = null;
            if (classMapping != null) {
                classMappingVal = classMapping.value().replace("/", "");
            }
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                RequestMapping mapping = method.getAnnotation(RequestMapping.class);
                if (mapping != null) {
                    String methodMappingVal = mapping.value().replace("/", "");
                    //String key = "/" + classMappingVal + "/" + methodMappingVal;
                    String key = "";

                    if (classMappingVal != null) {
                        key += ("/" + classMappingVal);
                    }
                    key += ("/" + methodMappingVal);
                    boolean b = Containers.mappingMethods.containsKey(key);
                    if (b) {
                        throw new RuntimeException("存在相同方法路径" + key);
                    } else {
                        System.out.println("初始化Controller:" + key);
                        Containers.mappingMethods.put(key, method);
                    }
                }
            }
        }
        //初始化解析器到容器
        Containers.resolvers.add(new IntResolver());
        Containers.resolvers.add(new BaseEntityResolver());
        Containers.resolvers.add(new HttpServletRequestResolver());
        Containers.resolvers.add(new HttpServletResponseResolver());
        Containers.resolvers.add(new HttpSessionResolver());
        Containers.resolvers.add(new StringResolver());
        Containers.resolvers.add(new RequestBodyResolver());


    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }


}
